package com.dognessnetwork.customer.controller.web;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.socket.sockjs.client.RestTemplateXhrTransport;

import com.dognessnetwork.customer.domain.ChatRoom;
import com.dognessnetwork.customer.domain.RoomStatus;
import com.dognessnetwork.customer.service.api.ChatRoomService;
import com.dognessnetwork.customer.service.impl.RestService;
import com.dognessnetwork.customer.util.SecurityUtils;
//import com.dognessnetwork.customer.service.api.RedisService;
import com.dognessnetwork.customer.util.StringToNumber;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.lang.Console;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/**
 * 
 * @author Dogness
 *
 */
@Controller
public class HandlerController {
    private   final   Logger   log =   LoggerFactory.getLogger(this.getClass());
    @Autowired
    HttpSession session;

    @Autowired
    ChatRoomService chatroomService;
    
    @Autowired
    RestService restService;
    
    @Autowired
    private MessageSource messageSource;

	@Autowired
    LocaleResolver localeResolver;

    @GetMapping("/")
    public String login() {
    	return "login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(HttpServletRequest request) {
        return "login";
    }

    /**
     * 客服入口
     * @param username
     * @param lang
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/customer")
    public String customer(String username,String	lang, HttpServletRequest request, HttpServletResponse response) {
        log.info(username);
        log.info("getId");
        // 查看客服是否第一次登录，如果不是则创建客服的坐席，如果是则更新状态为在线
        ChatRoom chatRoom = chatroomService.findBySeat(username);

        if (chatRoom == null) {
            ChatRoom newChatRoom = new ChatRoom();
            newChatRoom.setSeat(username);
            newChatRoom.setSeatAt(System.currentTimeMillis());
            newChatRoom.setStatus(RoomStatus.在线);
            chatroomService.save(newChatRoom);
        } else {
            Console.log("上线");
            chatRoom.setSeatAt(System.currentTimeMillis());
            chatRoom.setStatus(RoomStatus.在线);
            chatroomService.save(chatRoom);
        }
        String key = username;
        session.setAttribute("user", key);
        JSONObject mine = new JSONObject();
        mine.put("username", username);// 我的昵称
        mine.put("id", StringToNumber.letterToNumber(username));// 我的ID
        mine.put("status", "online");// 在线状态 online：在线、hide：隐身
        mine.put("sign", "CSD");// 我的签名
        mine.put("avatar", "/layui/images/img/tu2.png");// 我的头像
        mine.put("lang", lang.substring(0, 2).toLowerCase());
        session.setAttribute(key, mine+"");
        log.info("客服登录");
        return "redirect:index?key=" + username+"&lang="+lang;
    }

    @RequestMapping("/index")
    public String register() {
        return "index";
    }

    /**
     * 用户请求客服入口
     * 
     * @param username
     * @return
     */
    @RequestMapping("/requestCustomerService")
    public String message(String username,String	p, String token, HttpServletRequest request, String platForm, String area) {

        if (username == null)
            username = "hello";
        
        String	x_auth_token	=	restService.get_login_x_auth_token(token, username,p);
        JSONObject	userInfo	=	restService.getLoginUser(x_auth_token);
        JSONObject	header	=	JSONUtil.parseObj(userInfo.getStr("header"));
        if(header.getStr("status").equals("3019")) return "redirect:/";
        JSONObject	data	=	JSONUtil.parseObj(userInfo.getStr("data"));
        JSONObject mine = new JSONObject();
        String	nickname	=		data.getStr("nickname");
        mine.put("username", nickname);
        mine.put("token", x_auth_token);
        mine.put("platForm", platForm);
        mine.put("area", area);
        //session.setAttribute("petUserName", mine + "");
        //session.setAttribute(nickname, mine + "");
        request.getSession().setAttribute(nickname, mine + "");
        // request.getSession().setAttribute("username", username);
        // redisService.setStr("user", val);
        log.info("\nMINE:{}",session.getAttribute(nickname)+"");
        log.info("\n登录跳转x_auth_token:{},nickname{}",x_auth_token,nickname);

        return "redirect:userchat?username="+nickname+"&lang="+area;
    }

    @RequestMapping(value = "/userchat", method = RequestMethod.GET)
    public String userchat() {

        return "userchat";
    }

    @RequestMapping(value = "/chatRoom", method = RequestMethod.GET)
    public String chatRoom(String username) {

        String key = username;
        session.setAttribute("user", key);
        JSONObject mine = new JSONObject();
        mine.put("username", username);// 我的昵称
        mine.put("id", StringToNumber.letterToNumber(username));// 我的ID
        mine.put("status", "online");// 在线状态 online：在线、hide：隐身
        mine.put("sign", "PFU");// 我的签名
        mine.put("avatar", "/layui/images/img/tu2.png");// 我的头像
        // redisService.setStr(key, mine+"");
        log.info("登录");
        return "chatroom";
    }
    
    /**
     * 登出
     * @return
     */
    @RequestMapping("/logout")
    public String logout() {
        return "redirect:http://192.168.0.46:8888/logout";
    }
}